<?php
/**
 * Admin utils
 *
 * @author Anton
 */
class Lemar_Smtp
{
	/**
	 * Send message via a free SMTP server
	 * 
	 * @param array $message
	 */
	public static function send( $message )
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		
		$smtp = self::getOneFree();
		
		if($smtp != NULL)
		{
			$options = array(
				'username'	=> $smtp['login'],
				'password'	=> $smtp['password']
			);
			if (!empty($smtp['port']))
			{
				$options['port'] = $smtp['port']; // Default: 25
			}
			if (!empty($smtp['auth']))
			{
				$options['auth'] = $smtp['auth']; // Optionally: null, 'login', 'plain', 'crammd5'
			}
			if (!empty($smtp['ssl']))
			{
				$options['ssl'] = $smtp['ssl']; // Optionally: null, 'tls', 'ssl'
			}
			
			$transport = new Zend_Mail_Transport_Smtp($smtp['address'], $options);
			
			$mail = new Zend_Mail();
			$mail->setBodyText(strip_tags($message['message']));
			$mail->setBodyHtml($message['message']);
			$mail->addTo($message['address']);
			$mail->setSubject($message['subject']);
			$mail->setFrom($message['from'], ($message['from_name'])?$message['from_name']:NULL);
			
			// Set status of message in Queue to "processing"
			models_MessagequeMapper::edit(array('status' => 'processing'), $message['id']);
			
			if ($mail->send($transport))
			{
				// Delete message from Queue after it has been sent
				models_MessagequeMapper::delete($message['id']);
				// Write to statistic
				models_StatisticMapper::edit(
					array(
						'status' => 'sent',
						'sent_at' => new Zend_Db_Expr('NOW()'),
						'id_smtp' => $smtp['id']
					),
					$message['id_statistic']
				);
				// Mark used server
				self::used($smtp['id']);
			}
			else
			{
				// Set status of message in Queue to "new"
				models_MessagequeMapper::edit(array('status' => 'new'), $message['id']);
			}
			
			return $mail;
		}
	}
    
//----------------------------------------------------------------------------------------------------

	/**
	 * Test SMTP server
	 * 
	 * @param array $config
	 */
	public static function test( array $config )
	{
		$options = array(
			'username'	=> $config['login'],
			'password'	=> $config['password']
		);
		$options = array();
		if ($config['auth'] == 'login')
		{
			$connection = new Zend_Mail_Protocol_Smtp_Auth_Login($config['address'], $config['port'], $options);
		}
		else if ($config['auth'] == 'plain')
		{
			$connection = new Zend_Mail_Protocol_Smtp_Auth_Plain($config['address'], $config['port'], $options);
		}
		else if ($config['auth'] == 'crammd5')
		{
			$connection = new Zend_Mail_Protocol_Smtp_Auth_Crammd5($config['address'], $config['port'], $options);
		}
		else
		{
			$connection = new Zend_Mail_Protocol_Smtp($config['address'], $config['port'], (empty($config['ssl']))?array():array('ssl'=>$config['ssl']));
		}
		
		if ($connection instanceof Zend_Mail_Protocol_Smtp)
		{
			$connection->connect();
			$connection->auth();
			return true;
		}
		else
		{
			throw new Zend_Mail_Transport_Exception('Failed connecting to SMTP server: ' . $config['address']);
			return false;
		}
	}

//----------------------------------------------------------------------------------------------------

	/**
	 * Get one free SMTP server
	 */
	public static function getOneFree()
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		
		$clearResult = self::clearSmtpUsage();
		
		$select = $db->select()
				->from(
					array('s' => 'smtp'),
					array(  '*',
							'usage_count' => 'COUNT(u.id_smtp)'))
				->joinLeft(array('u' => 'smtp_usage'), 's.id = u.id_smtp', '')
				->group('s.id')
				->having('usage_count < s.emails_per_hour')
				->order(new Zend_Db_Expr('RAND()'))
				->limit(1);
		
		$result = $db->fetchAssoc($select);
		$result = array_pop($result);
		
		return $result;
	}

//----------------------------------------------------------------------------------------------------


	public static function getAllFree($page = null, $count = 0)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		
		$clearResult = self::clearSmtpUsage();
		
		$select = $db->select()
				->from(
					array('s' => 'smtp'),
					array(  '*',
							'usage_count' => 'COUNT(u.id_smtp)'))
				->joinLeft(array('u' => 'smtp_usage'), 's.id = u.id_smtp', '')
				->group('s.id')
				->having('usage_count < s.emails_per_hour')
				->order('s.id DESC');
		
		if ($page)
		{
			$countNewsOnPage = 0 == $count ? 100 : $count;
			
			$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
			$paginator->setItemCountPerPage($count)
					  ->setCurrentPageNumber($page);
			
			return $paginator;
		}
		else
		{
			$result = $db->fetchAssoc($select);
			
			return $result;
		}
	}
	    
//----------------------------------------------------------------------------------------------------

	/**
	 * Deletes all notes of usage of SMTP servers older than 1 hour
	 */
	public static function clearSmtpUsage()
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		
		$delete = $db->delete('smtp_usage', 'UNIX_TIMESTAMP(`timestamp`) < (UNIX_TIMESTAMP(NOW()) - 3600)');
		
		return $delete;
	}
	
//----------------------------------------------------------------------------------------------------

	/**
	 * Note one usage of SMTP server
	 * 
	 * @param int $smtp_id
	 */
	public static function used( $smtp_id )
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		
		$data = array('id_smtp' => $smtp_id );
		$result = $db->insert('smtp_usage', $data);
		
		return $result;
	}


//----------------------------------------------------------------------------------------------------

}
